package com.onion.utils.thread;

import com.google.common.util.concurrent.ThreadFactoryBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ThreadFactory;

public class ThreadHelper {

    private static Logger logger = LoggerFactory.getLogger(ThreadHelper.class);

    private static Object LOCK = new Object();
    private static Map<String, ThreadFactory> threadFactoryMap = new ConcurrentHashMap<>();

    public static void sleep(long timeInMillSec, String name) {
        try {
            Thread.sleep(timeInMillSec);
        } catch (InterruptedException exp) {
            logger.error("线程[{}]睡眠出错:{}", name, exp.getMessage());
        }
    }

    /**
     * 获取线程工厂
     * @param threadGroup
     * @return
     */
    public static ThreadFactory getTheadFactory(String threadGroup){
        ThreadFactory threadFactory = threadFactoryMap.get(threadGroup);
        if(threadFactory == null){
            synchronized (LOCK){
                threadFactory = threadFactoryMap.get(threadGroup);
                if(threadFactory == null){
                    threadFactory = new ThreadFactoryBuilder().setNameFormat(threadGroup + "_%d").build();
                    threadFactoryMap.put(threadGroup, threadFactory);
                }
            }
        }
        return threadFactory;
    }

}